﻿using System;
using System.Diagnostics;
using System.Reflection;

namespace Greycastle.RUBuildin
{
    internal static class AssemblyResolver
    {
        private static bool _resolverActive;

        public static void EnableResolutionFromManifestFolder()
        {
            if (_resolverActive)
                return;

            Debug.WriteLine("Activated AssemblyResolver for assembly {0}", typeof(AssemblyResolver).Assembly.FullName);

            _resolverActive = true;
            AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
        }

        private static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
        {
            var assemblyName = new AssemblyName(args.Name);
            var assemblyPath = "Greycastle.RUBuildin.Assemblies." + assemblyName.Name + ".dll";
            using (var manifestStream = typeof (AssemblyResolver).Assembly.GetManifestResourceStream(assemblyPath))
            {
                if (manifestStream == null)
                    return null;

                var buffer = new byte[manifestStream.Length];
                manifestStream.Read(buffer, 0, buffer.Length);

                return Assembly.Load(buffer);
            }
        }
    }
}